using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MVCDemoSoft2.Db;
using MVCDemoSoft2.Models;

namespace MVCDemoSoft2.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity//: IRepository<T>
    {
        private readonly DemoSoft2 _db;
        private readonly  DbSet<T> _table;
        public IQueryable<T> Table
        {
            get
            {
                return _table.AsQueryable<T>();
            }
        }
        public EfRepository()
        {
            _db = new DemoSoft2();
            _table = _db.Set<T>();
        }
        public void Delete(int id)
        {
            var entity = _table.FirstOrDefault(x => x.Id == id);
            entity.IsDeleted=true;
            entity.UpdatedTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public void Insert(T entity)
        {
            entity.IsActived=true;
            entity.IsDeleted=false;
            entity.CreatedTime=DateTime.Now;
            entity.UpdatedTime=DateTime.Now;
            entity.DisplayOrder=entity.DisplayOrder!=0?entity.DisplayOrder:0;

            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            entity.UpdatedTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}